package com.hunlian.makelove.net;

import android.content.Context;
import android.os.AsyncTask;

import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.tools.AesEncryptionUtil;
import com.hunlian.makelove.tools.LogTools;
import com.hunlian.makelove.tools.MyToast;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

public class HttpPostUploadUtil extends AsyncTask{



	/**
	 * 上传图片
	 * @param urlStr
	 * @param textMap
	 * @param fileMap
	 * @return
	 */
	private String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
		String res = "";
		HttpURLConnection conn = null;
		String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符  
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(14000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text  
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<String, String> entry = iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				//System.out.println("param: "+strBuf.toString());
				out.write(strBuf.toString().getBytes());
			}

			// file  
			if (fileMap != null) {
				Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<String, String> entry = iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					File file = new File(inputValue);
					String filename = file.getName();
					//MagicMatch match = Magic.getMagicMatch(file, false, true);
					//String contentType = match.getMimeType();
					
					FileNameMap fileNameMap = URLConnection.getFileNameMap();  
					String contentType = fileNameMap.getContentTypeFor(filename);  
					
					//System.out.println("contentType :"+contentType);
					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

					out.write(strBuf.toString().getBytes());

					DataInputStream in = new DataInputStream(new FileInputStream(file));
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据  
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			//System.out.println("发送POST请求出错。" + urlStr);
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		//System.out.println("res " + res);
		return res;
	}
	
	
		private String url = "";
		private Map<String, String> textMap;
		private Map<String, String> fileMap;
		IServiceReturnProcess proc;
		private Context context;
		
		public HttpPostUploadUtil(String url, Map<String, String> textMap, Map<String, String> fileMap, IServiceReturnProcess pro){
			this.url = url;
			this.textMap= textMap;
			this.fileMap= fileMap;
			this.proc = pro;
		}

		public static void doPost(String AUrl, Map<String, String> textMap, Map<String, String> fileMap, final IServiceReturnProcess pro){
			if (!AppApplication.networkAvailable) {
				MyToast.showShort("没有网络");
				return;
			}
			HttpPostUploadUtil call = new HttpPostUploadUtil(AUrl, textMap,fileMap, pro);
			//若直接使用call.execute()，则多个AsyncTask线程为串行执行，即要等到前一个线程执行完后，才会再执行第二个线程, 默认SERIAL_EXECUTOR，保证顺序执行
			//若使用call.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null)，则多个线程并行执行，不会存在第二个线程需要等第一个执行完后再执行的情况
			//但是，THREAD_POOL_EXECUTOR是一个corePoolSize为5的线程池，也就是说最多只有5个线程同时运行，超过5个的就要等待
			//若想同时执行超过5个的线程，则需要自己手动建立线程池了
			call.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new  Object[]{});
		}
		
		public boolean doPost(Context context, String AUrl, Map<String, String> textMap, Map<String, String> fileMap, final IServiceReturnProcess pro){
			if(!NetTools.isConnect(context)){
//				Intent intent = new Intent(context, NetAvailableActivity.class);
//				context.startActivity(intent);
				return false;
			}
			
			HttpPostUploadUtil call = new HttpPostUploadUtil(AUrl, textMap,fileMap, pro);
			call.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new  Object[]{});
			return true;
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			String stream = null;

			//对userId加密
			if(textMap.containsKey("userId")){
				String userId = textMap.get("userId");
				//对返回的json进行AES解密
				String ecryptParamter = AesEncryptionUtil.encrypt(userId,AesEncryptionUtil.Password,AesEncryptionUtil.Iv);
				textMap.put("userId",ecryptParamter);
			}
			System.out.println("textMap: "+textMap.toString());
			System.out.println("fileMap: "+fileMap.toString());
			stream = formUpload(url, textMap,fileMap);
			return stream;
		}

		@Override
		protected void onPostExecute(Object result) {
			String cReturn = (String)result;
			LogTools.e(cReturn);
			//解密
			//对返回的json进行AES解密
			String decryptSring = AesEncryptionUtil.decrypt(cReturn,AesEncryptionUtil.Password,AesEncryptionUtil.Iv);
			//System.out.println("decryptSring :"+decryptSring);
			proc.process(decryptSring);
		}

}